

function [f,gr] = mr_mle_2Nn_Nd2(b)

global dat
global dat2
global g
global D
global k

yy=0;
gra=zeros(1,2*k+0+3);

for i = 1:g
    yt = dat(i).yt;
    wt = dat(i).wt;
    xt = dat(i).xt;
    unobs = dat(i).unobs;
    Mg = dat2(i).Mg;
    
    [mr junk] = size(xt);   
     
  
    indp_b1=zeros(mr,1); 
    indp_b2=zeros(mr,1);
    gra_g=zeros(mr,2*k+0+3); 
    
     for j=1:D
    
        bb=xt*b(1:k+0)+wt*xt(:,1:k)*b(k+0+1:2*k+0)+Mg(:,j)*b(2*k+0+1)+b(2*k+0+2)*ones(mr,1)+exp(b(2*k+0+3))*unobs(:,j)*ones(mr,1); 
          
        indp_b1=indp_b1+ 1./(1+exp(-2*bb));
        indp_b2=indp_b2+ 1./(1+exp(2*bb));
     
        temp4=[xt wt*xt(:,1:k) Mg(:,j) ones(mr,1) unobs(:,j)*ones(mr,1)*exp(b(2*k+0+3))];  % remember to include the constant term.    
            
        gra_g=gra_g+temp4;
        
     end
   
    yy=yy+ ((ones(mr,1)+yt)'/2*log(indp_b1/D)+(ones(mr,1)-yt)'/2*log(indp_b2/D));
    
     
    gra1=2*((ones(mr,1)+yt)/2-indp_b1/D)'*gra_g/D;


    
    gra=gra+gra1;
end

    f=-yy;
    
    
    gr = -gra';
    